<template>
  <div class="group">
    <el-space>
      <el-input v-model="search.spuName" placeholder="请输入商品名称" />
      <el-input placeholder="请输入团购ID" v-model="search.id" clearable />
      <el-select placeholder="请选择团购状态" v-model="search.status" clearable>
        <el-option :label="item.label" :value="item.value" v-for="item in option" :key="item.value" />
      </el-select>
      <el-button :icon='Search' type='primary' @click="initData()">查找</el-button>
      <el-button :icon='Plus' type='primary' @click="addOrEdit(true)">添加</el-button>
    </el-space>
    <!-- 表格 -->
    <el-table :data="tableData" v-loading="loading" style="width: 100%;margin-top:10px" border :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
      <el-table-column type="expand">
        <template #default="scope">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="类目ID" width="120px">{{scope.row.categoryId}}</el-descriptions-item>
            <el-descriptions-item label="商品sku属性">
              <el-table :data='scope.row.groupShopSkuDTOList' :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" border>
                <el-table-column label="Skuid" prop="id">
                </el-table-column>
                <el-table-column label="规格标题" prop="title">
                </el-table-column>
                <el-table-column label="团购价格（元）" prop="skuGroupShopPrice">
                </el-table-column>
                <el-table-column label="库存" prop="stock">
                  <template #default='scope'>
                    {{scope.row.stock}}（件）
                  </template>
                </el-table-column>
                <el-table-column label="原始价格（元）" prop="originalPrice">
                </el-table-column>
                <el-table-column label="售卖价格（元）" prop="price">
                </el-table-column>
                <el-table-column label="会员价格（元）" prop="vipPrice">
                </el-table-column>
                <el-table-column label="国际条码" prop="barCode">
                </el-table-column>
              </el-table>
            </el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column label="团购ID" prop="id">
      </el-table-column>
      <el-table-column label="商品ID" prop="spuId">
      </el-table-column>
      <el-table-column label="商品名称" prop="title">
      </el-table-column>
      <el-table-column label="商品主图" prop="img">
        <template #default='scope'>
          <el-popover placement="right" trigger="hover" :width="400">
            <el-image :src='scope.row.img' />
            <template #reference>
              <el-image :src='scope.row.img' style="width:40px" />
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="未满策略">
        <template #default='scope'>
          <el-tag :type="scope.row.automaticRefund?'success':'warning'">{{scope.row.automaticRefund?'退款':'发货'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="活动状态">
        <template #default='scope'>
          <el-tag>{{scope.row.status?'进行':'冻结'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间">
        <template #default='scope'>
          {{new Date(scope.row.gmtStart).startTime()}}
        </template>
      </el-table-column>
      <el-table-column label="结束时间">
        <template #default='scope'>
          {{new Date(scope.row.gmtEnd).startTime()}}
        </template>
      </el-table-column>
      <el-table-column label="当前人数" prop="buyerNum">
      </el-table-column>
      <el-table-column label="目标人数" prop="minNum">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" type='primary' @click="addOrEdit(false,scope.row)" v-if="!scope.row.status">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-if="!scope.row.status">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Paging v-bind="pageData" @pageChang="pageChang"></Paging>
    <!-- 抽屉 -->
    <el-drawer v-model="drawer" direction="ltr" :show-close="false" size='50%' :destroy-on-close='true'>
      <template #title>
        <h4>{{boole?'创建商品':'修改商品'}}</h4>
        <el-button @click="drawer=false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
      <strong style="margin-left:20px">商品属性(spu)</strong>
      <el-form style="margin-top:20px" :model="form" label-position='left'>
        <el-form-item label='团购商品' label-width="120px">
          <el-cascader :options="commodity" v-model="form.spuId" :props="{emitPath:false,value:'id'}" style="margin-left:75px" @change="changeName" />
        </el-form-item>
        <el-form-item label='团购时间' label-width="120px">
          <el-date-picker type="datetime" placeholder="选择日期" v-model="form.gmtStart" style="margin-left:75px" value-format="x" />
          <span style="width:50px;text-align:center">至</span>
          <el-date-picker type="datetime" placeholder="选择日期" v-model="form.gmtEnd" value-format="x" />
        </el-form-item>
        <el-form-item label='团购基础人数' label-width="150px">
          <el-input-number v-model="form.minNum" :min="1" controls-position="right" style="margin-left:45px" />
        </el-form-item>
        <el-form-item label='活动结束时人数没有达到基础人数采取:' label-width="200px">
          <el-radio-group v-model="form.automaticRefund">
            <el-radio-button :label="0">不退款,我要发货</el-radio-button>
            <el-radio-button :label="1">自动退款,我不发货</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 卡片 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>商品类型(sku)</span>
            <el-popover trigger='click' placement='right' width="400px" ref="popover">
              <div>
                <span class="block">团购价格</span>
                <el-input-number controls-position="right" :min="1" v-model="groupPrice" />元
                <div style="margin-left:150px;margin-top:20px">
                  <el-button @click="$refs.popover.hide()">取消</el-button>
                  <el-button type='primary' @click="priceConfirm">确定</el-button>
                </div>
              </div>
              <template #reference>
                <el-button class="button" type='primary' @click="visible = true">批量定价</el-button>
              </template>
            </el-popover>
          </div>
        </template>
        <el-table :data="productList">
          <el-table-column label="Skuid" prop="id" />
          <el-table-column label="Sku条形码" prop="barCode" />
          <el-table-column label="类型名" prop="title" />
          <el-table-column label="库存" prop="stock" />
          <el-table-column label="现价/元" prop="price" />
          <el-table-column label="团购价格/元" prop="skuGroupShopPrice" />
          <el-table-column label="操作">
            <template #default='scope'>
              <el-button type='primary' @click="update(scope.$index,scope.row)">更新</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-drawer>
    <!-- 更新弹出框 -->
    <el-dialog v-model="dialogFormVisible" title="更新团购价格">
      <el-form label-width="auto" label-position='left'>
        <el-form-item label="团购价格">
          <el-input-number v-model="groupPrice" controls-position="right" />
        </el-form-item>
        <el-form-item label="现价">{{productList[ind].price}}</el-form-item>
        <el-form-item label="sku类型名">{{productList[ind].title}}</el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="upConfirm()">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Plus, Search } from '@element-plus/icons-vue';
import { post } from "@/utils/http";
import Paging from "@/components/Paging/Paging.vue";
export default {
  components: {
    Paging
  },
  setup() {
    return {
      Plus, Search
    }
  },
  data() {
    return {
      search: {
        spuName: '',  //搜索名称
        id: '', //搜索id
        status: null  //搜索状态
      },
      option: [{ label: '冻结', value: 0 }, { label: '活动', value: 1 }],
      tableData: [],  //表格数据
      pageData: {  //分页数据
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      drawer: false,  //抽屉显示
      form: {  //添加数据
        spuId: null,
        gmtStart: null,
        gmtEnd: null,
        minNum: 1,
        automaticRefund: 1,
        groupShopSkuList: []  //团购sku链表
      },
      commodity: [],  //商品数据
      productList: [], //商品类型列表
      groupPrice: null,  //团购价格
      dialogFormVisible: false,  //更新弹出框显示
      ind: 0,  //sku表格下标
      boole: true,
      loading: false
    }
  },
  methods: {
    initData() {
      this.loading = true
      let listData = {
        _gp: 'admin.groupshop',
        _mt: 'list',
        page: this.pageData.currentPage,
        limit: this.pageData.pageSize
      }
      post(this.search, listData).then(res => {
        if (200 == res.errno) {
          this.loading = false
          this.tableData = res.data.items
          this.pageData.total = res.data.total
        }
      })
    },
    relevanceData() {  //类目树形
      post({ _gp: 'admin.product', _mt: 'getSpuBigTree' }).then(res => {
        this.commodity = res.data
      })
    },
    // 团购价格确定
    priceConfirm() {
      this.productList.forEach(item => {//数组对象添加字段
        item.skuGroupShopPrice = this.groupPrice  //团购价格
        item.sku_id = item.id
      })
      this.$refs.popover.hide()
    },
    //分页
    pageChang(e) {
      Object.assign(this.pageData, e)
      this.initData()
    },
    // 添加或修改
    addOrEdit(boole, row) {
      this.boole = boole
      this.drawer = true
      if (boole) {
        Object.assign(this.form, this.$options.data().form)
        this.productList = []
      } else { //修改
        let { minNum, gmtEnd, gmtStart, automaticRefund, spuId, id } = row
        this.form = { minNum, gmtEnd, gmtStart, automaticRefund, spuId, id }
        this.productList = JSON.parse(JSON.stringify(row.groupShopSkuDTOList))  //深拷贝
      }
      if (this.commodity == '') this.relevanceData()  //数据只加载一次
    },
    // 选择团购商品
    changeName() {
      post({ _gp: 'admin.product', _mt: 'detail', spuId: this.form.spuId }).then(res => {
        if (200 == res.errno) {
          this.productList = res.data.skuList
        } else {
          ElMessage.error(res.errmsg)
        }
      })
    },
    // 添加确定
    confirm() {
      this.form.groupShopSkuList = JSON.stringify(this.productList)
      if (!this.form.spuId) return ElMessage.error('请选择商品')
      if (this.boole) {  //添加
        post({ _gp: 'admin.groupshop', _mt: 'create', ...this.form }).then(res => {
          if (200 == res.errno) {
            this.drawer = false
            ElMessage.success('成功')
            this.initData()
          } else {
            ElMessage.error(res.errmsg)
          }
        })
      } else { //修改
        post({ _gp: 'admin.groupshop', _mt: 'edit', ...this.form }).then(res => {
          if (200 == res.errno) {
            this.drawer = false
            ElMessage.success('成功')
            this.initData()
          } else {
            ElMessage.error(res.errmsg)
          }
        })
      }
    },
    // 更新
    update(index, row) {
      this.groupPrice = row.skuGroupShopPrice
      this.ind = index
      this.dialogFormVisible = true
    },
    //更新确定
    upConfirm() {
      this.dialogFormVisible = false
      this.productList[this.ind].skuGroupShopPrice = this.groupPrice
    },
    // 删除
    handleDelete(row) {
      ElMessageBox.confirm(
        '是否要删除当行数据?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          post({ _gp: 'admin.groupshop', _mt: 'delete', id: row.id }).then(res => {
            if (200 == res.errno) {
              ElMessage.success('成功')
              this.initData()
            }
          })
        })
    }
  },
  created() {
    this.initData()
  },
}
</script>

<style lang="less" scoped>
/deep/#el-drawer__title {
  margin: 0px;
}
/deep/.el-drawer__body {
  padding: 0px;
}
/deep/.el-descriptions {
  margin-left: 20px;
}
/deep/.el-form-item__label {
  padding-left: 40px;
}
.button {
  float: right;
}
.box-card {
  margin-top: 30px;
}
.block {
  display: inline-block;
  width: 150px;
  text-align: center;
}
/deep/.el-overlay {
  z-index: 3 !important;
}
</style>